package com.xiaomo.gitee.datamanager.service.menu.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaomo.gitee.datamanager.dto.menu.DataMenuDTO;
import com.xiaomo.gitee.datamanager.entity.menu.DataMenuPO;
import com.xiaomo.gitee.datamanager.mapper.menu.DataMenuMapper;
import com.xiaomo.gitee.datamanager.service.menu.DataMenuService;
import com.xiaomo.gitee.datamanager.util.AuthorizeUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class DataMenuServiceImpl extends ServiceImpl<DataMenuMapper, DataMenuPO> implements DataMenuService {

    private final DataMenuMapper dataMenuMapper;

    @Override
    public List<DataMenuDTO> resolveMenu() {
        List<String> perms = AuthorizeUtils.getPermissions();
//        List<String> perms = Arrays.asList("ROLE_user","ROLE_admin");

        List<DataMenuPO> dataMenuPOList = dataMenuMapper.selectAll();
        Map<Integer, DataMenuDTO> dataMenuDTOMap = dataMenuPOList.stream().collect(Collectors.toMap(DataMenuPO::getId, this::transfer));

        dataMenuDTOMap.forEach((id, dataMenuDTO) -> {
            if (dataMenuDTO.getParentId() != null) {
                    dataMenuDTOMap.get(dataMenuDTO.getParentId()).getChildren().add(dataMenuDTO);
            }
        });

        dataMenuDTOMap.keySet().stream().toList().forEach(id -> {
            DataMenuDTO tempDTO = dataMenuDTOMap.get(id);
            if (!perms.contains(tempDTO.getPerm()) || tempDTO.getParentId() != null) {
                dataMenuDTOMap.remove(id);
            }
        });

        return dataMenuDTOMap.values().stream().toList();
    }

    private DataMenuDTO transfer(DataMenuPO po) {
        DataMenuDTO dto = new DataMenuDTO();
        dto.setId(po.getId());
        dto.setName(po.getName());
        dto.setDescription(po.getDescription());
        dto.setPath(po.getPath());
        dto.setIcon(po.getIcon());
        dto.setChildren(new ArrayList<>());
        dto.setPerm(po.getPerm());
        dto.setParentId(po.getParentId());
        return dto;
    }

}
